var station = "Novosibirsk";
var period = 2;

function loadOptions(){
	
	if(!localStorage["location"]){
		alert("Locations is not defined! Use default: Novosibirsk");
		station = "Novosibirsk";
	} else {
		station = localStorage["location"];
	}
	
	if(!localStorage["period"]){
		alert("Update interval is not defined! Use default: 2 minutes");
		period = 2;
	} else {
		period = localStorage["period"];
	}
}

var url	= "http://www.wunderground.com/";
var XMLurl	= "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml";

function goToWeather(){
	chrome.tabs.create({url: url});
}

function init(){
	loadOptions();
	window.setTimeout(startUpdate,0);
}

function scheduleRequest(){
	window.setTimeout(startUpdate,period * 60000);
}

function startUpdate(){	
	getXML();
	scheduleRequest();
}

function getXML(){
	$.ajax({
		url: 	XMLurl,
		type:	"GET",
		data: 	({query : station}),
		cache:	false,
		timeout: 5000,
		dataType: 'xml',
		error: function(){
			chrome.browserAction.setTitle({title : "Error"});
			url = baseUrl();
		},
		success: function(xml){
		
			url = getNode(xml,"forecast_url");
			
			// Generate weather report for title
			title = jQuery.sprintf(
					"Temperature: %s, Condition: %s,  Wind %.1f %s %s, %s %d",
					getNode(xml,"temp_c"),			
					getNode(xml,"weather"),					
					getNode(xml,"wind_mph") * 0.444,
					"m/s",
					getNode(xml,"wind_dir"),
					"Pressure:",
					getNode(xml,"pressure_in") * 25.4);
			iconPath = "wc/"+getNode(xml,"icon")+".GIF";
			//Working with Address bar icon
			chrome.browserAction.setIcon({path: iconPath});
			chrome.browserAction.setBadgeBackgroundColor({color: [80, 80, 250, 200]});
			chrome.browserAction.setBadgeText({text : getNode(xml,"temp_c")});		
			chrome.browserAction.setTitle({title : title});
		}
	});
}

function getNode(xml,str){
	return $(xml).find(str).text();
}